package apis

import (
	"fmt"
	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/httpmvc/api"
	"gitee.com/sansaniot/ssiot-core/httpmvc/jwtauth/user"
	"gitee.com/sansaniot/ssiot-core/serrors"
	"github.com/gin-gonic/gin"
	"ssadmin/common/constant"
	"ssadmin/internal/admin/models"
	"ssadmin/internal/admin/models/command"
	"ssadmin/internal/admin/models/query"
	"ssadmin/internal/admin/service"
)

type SysLogo struct {
	api.Api
}

// Get 获取logo
func (e SysLogo) Get(c *gin.Context) {
	req := query.SysLogoReq{}
	s := service.SysLogo{}

	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors

	if err != nil {
		e.Logger.Error(err)
		e.Fail(serrors.Fail)
		return
	}

	userId := user.Get(c, constant.CacheKeyUserId).(string)
	creatorId := user.Get(c, constant.CacheKeyCreatorId).(string)
	agencyId := user.Get(c, constant.CacheKeyAgencyId).(string)

	// 非租户，非admin，查询所属租户信息
	if creatorId != "1" {
		req.UserId = agencyId
	} else if userId != "1" {
		// 普通租户 token对应用户的信息
		req.UserId = userId
	} else if userId == "1" && req.UserName == "" {
		req.UserId = userId
	}

	req.Systemid = c.GetHeader(constant.CacheKeySystemId)

	var sysLogoModel models.SysLogo
	err = s.Get(&req, &sysLogoModel)
	if err != nil {
		e.Fail(serrors.Fail)
		return
	}
	e.Data(sysLogoModel)
}

// Save 保存
func (e SysLogo) Save(c *gin.Context) {
	req := command.SysLogoReq{}
	s := service.SysLogo{}

	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors

	if err != nil {
		e.Logger.Error(err)
		e.Fail(serrors.Fail)
		return
	}

	// 当前用户的信息
	userId := user.Get(c, constant.CacheKeyUserId).(string)
	userName := user.Get(c, constant.CacheKeyUserName).(string)
	creatorId := user.Get(c, constant.CacheKeyCreatorId).(string)

	if creatorId != "1" {
		e.Fail(0, "只有租户可以修改系统信息")
		return
	} else if userId != "1" {
		// 普通租户
		req.UserId = userId
		req.UserName = userName
	} else {
		// admin 如果没有传入了用户名, 则保存admin自己的信息
		if req.UserName == "" {
			req.UserId = userId
			req.UserName = userName
		} else {
			key := fmt.Sprintf("login_user:%s", req.UserName)
			req.UserId, _ = env.Cache.HashGet(key, constant.CacheKeyUserId)
		}
	}

	req.Systemid = c.GetHeader(constant.CacheKeySystemId)

	err = s.Save(&req)
	if err != nil {
		e.Fail(serrors.Fail)
		return
	}

	e.Data(req.Id)
}
